import axios from 'axios';
import store from '@/store';
import { Toast, Notify } from 'vant';
// 根据环境不同引入不同api地址
import { baseApi } from '@/config';
import router from "../../router";
// create an axios instance
const service = axios.create({
	//自定义配置
	baseURL: baseApi, // url = base api url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 10 * 1000 // request timeout 10秒 超时
});
// request拦截器 request interceptor
service.interceptors.request.use(
	(config) => {
		// 不传递默认开启loading
		if (!config.hideloading) {
			// loading
			Toast.loading({
				forbidClick: true
			});
		}

    if (config.url == '/api/upload/image') {
      config.headers['Content-Type'] = 'multipart/form-data';
      config.headers['Accept'] = 'multipart/form-data';
    }
		if (localStorage.getItem("token")) {
			config.headers['Authorization'] = localStorage.getItem("token");
		}
		return config;
	},
	(error) => {
		// do something with request error
		console.log(error); // for debug
		return Promise.reject(error);
	}
);
// respone拦截器
service.interceptors.response.use(
	(response) => {
	  console.log(response)
    if (response.headers.Authorization||response.headers.authorization){
      // 监测响应头如果token过期，header头里会返回新的token，字段名【Authorization】，替换本地token
      localStorage.setItem("token", response.headers.Authorization||response.headers.authorization);
    }
		Toast.clear();
		const res = response.data;
    if (res.err_code && res.err_code !== 200) {
      Notify({ type: 'danger', message: res.msg })
      if (res.err_code == 4001) {
        // 登录超时,重新登录
        router.push({name:'login'})
        return Promise.reject(res || 'error');
      }
      return Promise.reject(res || 'error');
    } else {
      return Promise.resolve(res);
    }
    },
	(error) => {
		Toast.clear();
		console.log('err' + error); // for debug
		return Promise.reject(error);
	}
);

export default service;
